﻿using System;
using System.Web.Routing;
using BugManager;
using ChannelVN.Cached.UrlRewrite;
using Combres;
using System.Web;
using System.Text.RegularExpressions;

namespace GUI
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.AddCombresRoute("Combres");
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var url = Context.Request.Url.AbsolutePath;

            if (UrlRewriteModule.IsMobileRedirect(Context) || UrlRewriteModule.isMobileBrowser(Context))
            {
                if (!UrlRewriteModule.IsExistCookieNoRedirect())
                {
                    if (url.Contains(".chn") || url.Contains(".htm"))
                    {
                        url = url.Replace(".chn", ".htm");
                        Context.Response.Redirect("http://m.soha.vn" + url);
                    }
                    else
                        Context.Response.Redirect("http://m.soha.vn");
                    Response.End();
                }
            }
            if (url.StartsWith("/Handlers/"))
            {
                Context.Response.Redirect("/");
                Response.End();
            }
        }



        protected void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().GetBaseException();

            if (ex is HttpException)
            {
                if (Regex.IsMatch(HttpContext.Current.Request.RawUrl, "[^/a-zA-Z0-9-]+"))
                {
                    _301Redirection.RedirectTo(Regex.Replace(HttpContext.Current.Request.RawUrl, "[^/a-zA-Z0-9-.]+", string.Empty));
                    return;
                }
                //if (HttpContext.Current.Request.RawUrl.IndexOfAny(new[] { '*' }) != -1)
                //{
                //    _301Redirection.RedirectTo(Regex.Replace(HttpContext.Current.Request.RawUrl, "[*]+", string.Empty));
                //    return;
                //}
            }

            ErrorManager.Log(ex);
        }
    }
}